package com.firsteapps.mobile.android.puzzle;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.firsteapps.mobile.android.puzzle.game.DrawView;
import com.firsteapps.mobile.android.puzzle.game.Helper;
import com.firsteapps.mobile.android.puzzle.game.Puzzle;
import com.firsteapps.mobile.android.puzzle.game.PuzzleInfo;
import com.firsteapps.mobile.android.puzzle.util.Consts;
import com.firsteapps.mobile.android.puzzle.util.Utilities;

public class ImportPuzzle extends PostLoginBase {

	private ListView puzzlesList;
	private TextView puzzleSizeViewer, movesCountViewer, attemptsCountViewer, timeLimitViewer, autosolveViewer;
	private DrawView puzzlePreview;
	private ImageView importButton, preview; // , winPrizes;
	private LinearLayout importPuzzlesLayout, puzzleViewerLayout;
	private boolean isPreviewOn = false;
	// private int currentItemPosition = -1;
	private boolean[] selectedPositions;
	private PuzzleInfo info = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.import_puzzle);

		Intent intent = getIntent();
		System.out.println(intent != null ? intent.getAction() + "" : "Null Intent");

		puzzleSizeViewer = (TextView) findViewById(R.id.puzzle_size_viewer);
		movesCountViewer = (TextView) findViewById(R.id.moves_count_viewer);
		attemptsCountViewer = (TextView) findViewById(R.id.attempts_count_viewer);
		timeLimitViewer = (TextView) findViewById(R.id.time_limit_viewer);
		autosolveViewer = (TextView) findViewById(R.id.autosolve_viewer);

		puzzlesList = (ListView) findViewById(R.id.external_puzzles_list);
		puzzlesList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

		puzzlePreview = (DrawView) findViewById(R.id.puzzleView);
		importPuzzlesLayout = (LinearLayout) findViewById(R.id.import_puzzles_layout);
		puzzleViewerLayout = (LinearLayout) findViewById(R.id.puzzle_viewer_layout);

		String[] importItems = Helper.getExternalPuzzles(ImportPuzzle.this);
		selectedPositions = new boolean[importItems == null ? 0 : importItems.length];
		Helper.resetSelectedItem(selectedPositions);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item_puzzles, importItems) {
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				if (convertView == null) {
					LayoutInflater inflater = (LayoutInflater) ImportPuzzle.this
							.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					convertView = inflater.inflate(R.layout.list_item_puzzles, null);
				}

				ImageView selectionView = (ImageView) convertView.findViewById(R.id.puzzle_item_state);
				TextView nameView = (TextView) convertView.findViewById(R.id.puzzle_item_name);
				TextView dateView = (TextView) convertView.findViewById(R.id.puzzle_item_date);
				TextView autosolveView = (TextView) convertView.findViewById(R.id.puzzle_item_autosolvable);

				selectionView.setBackgroundResource(selectedPositions[position] ? R.drawable.puzzle_selected
						: R.drawable.puzzle_not_selected);
				String currentItem = getItem(position);
				String[] puzzleAttrs = currentItem.substring(currentItem.lastIndexOf("/") + 1).split(Consts.FILENAME_SPLITTER);
				nameView.setText(puzzleAttrs[0].substring(0, puzzleAttrs[0].indexOf(".")));
				String dateStr;
				if (puzzleAttrs.length > 1) {
					dateStr = puzzleAttrs[1];
					dateStr = dateStr.replaceFirst("_", "/");
					dateStr = dateStr.replaceFirst("_", "/");
					dateStr = dateStr.replaceFirst("_", " ");
					dateStr = dateStr.replaceFirst("_", ":");
					dateStr = dateStr.replaceFirst("_", ":");
				} else
					dateStr = "Not specified";
				dateView.setText(dateStr);
				autosolveView.setText(puzzleAttrs.length > 2 ? puzzleAttrs[2] : "Not specified");

				return convertView;
			}
		};
		puzzlesList.setOnItemClickListener(new OnItemClickListener() {
			@SuppressWarnings("unchecked")
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (!selectedPositions[position]) {
					Helper.resetSelectedItem(selectedPositions);
					selectedPositions[position] = true;
					// ImageView selectedPuzzle = (ImageView) view.findViewById(R.id.puzzle_item_state);
					// selectedPuzzle.setBackgroundResource(R.drawable.puzzle_selected);

					String puzzleName = (String) parent.getItemAtPosition(position);
					Helper.decompress(ImportPuzzle.this, puzzleName, Consts.FOLDER_NAME_TEMP, true);
					String infoPath = Consts.FOLDER_NAME_TEMP + "/puzzle" + Consts.FILE_TYPE_INFO;
					info = Helper.loadCreatedPuzzle(ImportPuzzle.this, infoPath);

					if (info == null) {
						Helper.doMessageDialog(ImportPuzzle.this, "Import Puzzle", "Unable to load the puzzle");
					} else {
						TextView dateView = (TextView) view.findViewById(R.id.puzzle_item_date);
						TextView autosolveView = (TextView) view.findViewById(R.id.puzzle_item_autosolvable);
						dateView.setText(info.getCreationDate());
						autosolveView.setText(info.isAutosolvable() ? "YES" : "NO");

						puzzleSizeViewer.setText(info.getSize() + ":" + info.getSize());
						movesCountViewer.setText(info.getMoveCount() + (info.getMaxMoves() > 0 ? "/" + info.getMaxMoves() : ""));
						attemptsCountViewer.setText(info.getAttempts()
								+ (info.getMaxAttempts() > 0 ? "/" + info.getMaxAttempts() : ""));
						timeLimitViewer.setText(Helper.getElapsedTime(info.getElapsed())
								+ (info.getMaxTime() > 0 ? "/" + Helper.getElapsedTime(info.getMaxTime() * 1000) : ""));
						autosolveViewer.setText(info.isAutosolvable() ? "YES" : "NO");
					}

					((ArrayAdapter<String>) parent.getAdapter()).notifyDataSetChanged();
					// currentItemPosition = position;
				}
			}
		});
		puzzlesList.setAdapter(adapter);

		importButton = (ImageView) findViewById(R.id.ip_import_puzzle);
		importButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				int position = puzzlesList.getCheckedItemPosition();
				if (position < 0) {
					Helper.doMessageDialog(ImportPuzzle.this, "Import Puzzle", "No item is selected");
				} else {
					AlertDialog dialog = new AlertDialog.Builder(ImportPuzzle.this).setTitle("Import Puzzle")
							.setMessage("Are you sure you want to import the puzzle?")
							.setPositiveButton(android.R.string.ok, new android.content.DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									if (info == null) {
										Helper.doMessageDialog(ImportPuzzle.this, "Import Puzzle",
												"Unable to load selected puzzle");
									} else {
										if (Helper.registerPuzzle(ImportPuzzle.this, Consts.FOLDER_NAME_REGISTERED_PUZZLES,
												info.getPuzzleId())) {
											StringBuffer messages = new StringBuffer();
											String imgFileName = Helper.importFile(ImportPuzzle.this, messages,
													Consts.FOLDER_NAME_TEMP + "/puzzle" + Consts.FILE_TYPE_PUZZLE,
													Consts.FILE_TYPE_PUZZLE, getWorkingSubDirectory(Consts.FOLDER_NAME_IMPORTED));

											String alterFileName = "NoImage";
											if (info.getAlternativeImage() != null)
												alterFileName = Helper.importFile(ImportPuzzle.this, messages,
														Consts.FOLDER_NAME_TEMP + "/puzzle" + Consts.FILE_TYPE_ALTERNATIVE,
														Consts.FILE_TYPE_ALTERNATIVE,
														getWorkingSubDirectory(Consts.FOLDER_NAME_IMPORTED));

											if (messages.length() > 0 || imgFileName == null || alterFileName == null) {
												Helper.doMessageDialog(ImportPuzzle.this, "Import Puzzle",
														"Unable to load selected puzzle");
											} else {
												info.setFile(imgFileName);
												if (!alterFileName.equals("NoImage"))
													info.setAlternativeImage(alterFileName);

												Helper.saveCreatedPuzzle(ImportPuzzle.this, info,
														getWorkingSubDirectory(Consts.FOLDER_NAME_IMPORTED));

												Utilities.startActivityWithAnimation(ImportPuzzle.this, PostLogin.class);
											}
										} else {
											Helper.doMessageDialog(ImportPuzzle.this, "Import Puzzle",
													"Selected puzzle has already been imported");
										}
									}
								}
							}).setNegativeButton(android.R.string.cancel, new android.content.DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
								}
							}).create();
					dialog.show();
				}
			}
		});

//		winPrizes = (ImageView) findViewById(R.id.ip_win_prizes);

		preview = (ImageView) findViewById(R.id.ip_preview);
		preview.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (isPreviewOn) {
					puzzleViewerLayout.setVisibility(View.GONE);
					importPuzzlesLayout.setVisibility(View.VISIBLE);
					// winPrizes.setVisibility(View.GONE);
					// importButton.setVisibility(View.VISIBLE);
					isPreviewOn = !isPreviewOn;
				} else {
					int position = puzzlesList.getCheckedItemPosition();
					if (position < 0) {
						Helper.doMessageDialog(ImportPuzzle.this, "Import Puzzle", "No item is selected");
					} else {
						if (info == null) {
							Helper.doMessageDialog(ImportPuzzle.this, "Import Puzzle", "Unable to load selected puzzle");
						} else {
							// winPrizes.setVisibility(View.VISIBLE);
							// importButton.setVisibility(View.GONE);
							importPuzzlesLayout.setVisibility(View.GONE);
							puzzleViewerLayout.setVisibility(View.VISIBLE);

							info.setTilePositions(null);
							puzzlePreview.setPuzzleSize(info.getSize());
							String tempImgPath = Consts.FOLDER_NAME_TEMP + "/puzzle" + Consts.FILE_TYPE_PUZZLE;
							Puzzle puzzle = new Puzzle(Helper.getBitmap(ImportPuzzle.this, tempImgPath), info);
							puzzlePreview.setFocusable(false);
							puzzlePreview.setPuzzle(puzzle);

							isPreviewOn = !isPreviewOn;
						}
					}
				}
			}
		});
	}
}
